package com.adtech.farmProducts.activities.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.adtech.farmProducts.base.BaseNfcActivity;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.AccountManagers;
import com.adtech.common.widgets.recycler.RecyclerViewAdapter;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.adapter.BillingInfoAdapter;
import com.adtech.farmProducts.base.BaseActivity;
import com.adtech.farmProducts.base.BillingTypeInfo;
import com.adtech.farmProducts.model.BillingType;
import com.adtech.farmProducts.model.CardBean;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 计费详情修改
 */
public class BillingInfoActivity extends BaseNfcActivity implements BillingInfoAdapter.onClickListener {

    @BindView(R.id.title)
    TextView mTitle;
    @BindView(R.id.layout_base)
    LinearLayout layout_base;
    @BindView(R.id.ed_name)
    EditText ed_name;
    @BindView(R.id.recycler_view)
    public RecyclerView mRecyclerView;
    @BindView(R.id.tv_mf_time)
    TextView tv_mf_time;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_price)
    TextView tv_price;

    /**
     * DATA
     */
    private BillingInfoAdapter billingInfoAdapter;
    private BillingType billingType;

    public static void show(Context context, BillingType billingType) {
        Intent intent = new Intent(context, BillingInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("BillingType", billingType);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_billing;
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        billingType = (BillingType) bundle.getSerializable("BillingType");
        return super.initArgs(bundle);
    }

    private int page = 1;

    @Override
    protected void initData() {
        super.initData();
        mTitle.setText("编辑计费模板");
        ed_name.setText(billingType.getTempname());
        setFreeShow();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        billingInfoAdapter = new BillingInfoAdapter(new RecyclerViewAdapter.AdapterListenerImpl<BillingTypeInfo>() {
            @Override
            public void onItemClick(RecyclerViewAdapter.ViewHolder<BillingTypeInfo> holder, BillingTypeInfo data) {
                super.onItemClick(holder, data);
            }
        });
        mRecyclerView.setAdapter(billingInfoAdapter);
        billingInfoAdapter.setBillingInfoOnClickListener(this);
        billingInfoAdapter.replace(billingType.getConfig());
        initCustomOptionPicker();
    }

    @OnClick({R.id.btn_right, R.id.btn_save,R.id.layout_free,R.id.btn_default})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_right:
                break;
            case R.id.layout_free://免费等待时长
                optionsFree();
                break;
            case R.id.btn_save:
                String modelName = ed_name.getText().toString();
                if (TextUtils.isEmpty(modelName)) {
                    App.getInstance().showMessage("请给模板设置名称！");
                    return;
                }
                billingType.setTempname(modelName);
                setDriverPriceConfig();
                break;
            case R.id.btn_default://设置为默认模板
                setPriceModelDefault();
                break;
        }
    }


    /**
     * 设置我的计价模板
     */
    private void setDriverPriceConfig() {
        loadingDialogShow(true);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("temp_id", billingType.getTemp_id());
        asyncHttpPostFormData.addFormData("tempname", billingType.getTempname());
        asyncHttpPostFormData.addFormData("waitfree", billingType.getWaitfree());
        asyncHttpPostFormData.addFormData("chaochuwait", billingType.getChaochuwait());
        asyncHttpPostFormData.addFormData("chaochuwaitprice", billingType.getChaochuwaitprice());
        asyncHttpPostFormData.addFormData("configJson", new Gson().toJson(billingType.getConfig()));
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/setDriverPriceConfig", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<BillingType>>() {
                }.getType();
                RspModel<BillingType> rspModel = getAnalysis(response, type, "设置我的计价模板");
                if (rspModel == null) {
                    App.getInstance().showMessage("计费模板保存失败！");
                    return;
                }
                if (rspModel.getData() != null && rspModel.getCode() == 200) {
                    App.getInstance().showMessage("计费模板保存成功！");
                    setResult(100);
                    finish();
                } else {
                    App.getInstance().showMessage(rspModel.getMessage());
                }
            }
        });
    }

    /**
     * 设置为默认模板
     */
    private void setPriceModelDefault() {
        loadingDialogShow(true);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("temp_id", billingType.getTemp_id());
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/setDriverPriceTempDefault", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<BillingType>>() {
                }.getType();
                RspModel<BillingType> rspModel = getAnalysis(response, type, "设置为默认模板");
                if (rspModel == null) {
                    App.getInstance().showMessage("设置为默认模板失败！");
                    return;
                }
                if (rspModel.getData() != null && rspModel.getCode() == 200) {
                    App.getInstance().showMessage("设置为默认模板成功！");
                    setResult(100);
                    finish();
                } else {
                    App.getInstance().showMessage(rspModel.getMessage());
                }
            }
        });
    }

    @Override
    public void onClickButton(int value, final int position, BillingTypeInfo data) {
        switch (value) {
            case 0:
                final List<String> listQbj = new ArrayList<>();
                for (int i = 10; i < 100; i++) {
                    listQbj.add(i + "元");
                }
                OptionsPickerView optionsPickerViewCLCJ = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        String value = listQbj.get(options1);
                        billingType.getConfig().get(position).setQibuprice(value.replace("元", ""));
                        billingInfoAdapter.notifyDataSetChanged();
                    }
                }).build();
                optionsPickerViewCLCJ.setPicker(listQbj);
                optionsPickerViewCLCJ.show();
                break;
            case 1:
            case 2:
                optionsPicker(position);
                break;
        }
    }

    private void optionsPicker(final int position) {
        final List<String> listQblc = new ArrayList<>();
        final List<String> listClc = new ArrayList<>();
        final List<String> listCcj = new ArrayList<>();
        for (int i = 1; i < 8; i++) {
            listQblc.add("起步" + i + "公里");
            listClc.add("超出后每" + i + "公里");
            listCcj.add("加收" + (4 + i) + "元");
        }
        OptionsPickerView optionsPickerViewCLCJ = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                BillingTypeInfo billingTypeInfo = billingType.getConfig().get(position);
                billingTypeInfo.setQibukm(listQblc.get(options1).replace("起步", "").replace("公里", ""));
                billingTypeInfo.setChaochukm(listClc.get(options2).replace("超出后每", "").replace("公里", ""));
                billingTypeInfo.setChaochuprice(listCcj.get(options3).replace("加收", "").replace("元", ""));
                billingInfoAdapter.notifyDataSetChanged();
            }
        }).build();
        optionsPickerViewCLCJ.setNPicker(listQblc, listClc, listCcj);
        optionsPickerViewCLCJ.show();
    }

    /**
     * 免费等待设置
     */
    private void optionsFree() {
        final List<String> listFreeTime = new ArrayList<>();
        final List<String> listTime = new ArrayList<>();
        final List<String> listPrice = new ArrayList<>();
        for (int i = 1; i < 8; i++) {
            listFreeTime.add("免费等待" + i + "分钟");
            listTime.add("超出后每" + i + "分钟");
            listPrice.add("收取等候费" + (4 + i) + "元");
        }
        OptionsPickerView optionsPickerViewCLCJ = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                billingType.setWaitfree(listFreeTime.get(options1).replace("免费等待", "").replace("分钟", ""));
                billingType.setChaochuwait(listTime.get(options2).replace("超出后每", "").replace("分钟", ""));
                billingType.setChaochuwaitprice(listPrice.get(options3).replace("收取等候费", "").replace("元", ""));
                setFreeShow();
            }
        }).build();
        optionsPickerViewCLCJ.setNPicker(listFreeTime, listTime, listPrice);
        optionsPickerViewCLCJ.show();
    }

    private void setFreeShow(){
        tv_mf_time.setText(String.format("%s分钟",billingType.getWaitfree()));
        tv_time.setText(String.format("%s分钟",billingType.getChaochuwait()));
        tv_price.setText(String.format("%s元",billingType.getChaochuwaitprice()));
    }


    private OptionsPickerView pvCustomOptions;
    private ArrayList<CardBean> cardItem = new ArrayList<>();

    private void initCustomOptionPicker() {//条件选择器初始化，自定义布局
        for (int i = 0; i < 5; i++) {
            cardItem.add(new CardBean(i, "No.ABC12345 " + i));
        }
        /**
         * @description
         *
         * 注意事项：
         * 自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针。
         * 具体可参考demo 里面的两个自定义layout布局。
         */
        pvCustomOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                //String tx = cardItem.get(options1).getPickerViewText();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptions.returnData();
                                pvCustomOptions.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptions.dismiss();
                            }
                        });
                    }
                })
                .isDialog(true)
                .build();
        pvCustomOptions.setPicker(cardItem);//添加数据
    }
}
